package com.heima.wemedia.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.constants.WmNewsMessageConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.utils.threadlocal.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private WmNewAutoScanService wmNewAutoScanService;
//    @Autowired
//    private ApUserFeignClient apUserFeignClient;


    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmNewsPageReqDto dto) {
        //1.非空判断
        dto.checkParam();
        //2.分页查询
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmNews> queryWrapper = Wrappers.lambdaQuery();
        //2.1 根据状态查询
        if (dto.getStatus() != null) {
            queryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        //2.2 根据关键字查询
        if (!StringUtils.isEmpty(dto.getKeyword())) {
            queryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }

        //2.3 根据频道id查询
        if (dto.getChannelId() != null) {
            queryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }

        //2.4 根据开始和结束时间查询
        if (dto.getBeginPubdate() != null && dto.getEndPubdate() != null) {
            queryWrapper.between(WmNews::getPublishTime, dto.getBeginPubdate(), dto.getEndPubdate());
        }

        //2.5 根据登录用户id查询
        queryWrapper.eq(WmNews::getUserId, WmThreadLocalUtil.getUser().getId());
        queryWrapper.orderByDesc(WmNews::getCreatedTime);

        page = super.page(page, queryWrapper);

        //3.返回数据结果
        ResponseResult result = new PageResponseResult(dto.getPage(), dto.getSize(), (int) page.getTotal());
        result.setData(page.getRecords());
        return result;
    }

    /**
     * 保存-修改-提交草稿为一体的方法
     * 主方法
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult submit(WmNewsDto dto) {
        log.info(" WmNewsDto,{}", dto);
        //先进行必要参数的校验
        if (StrUtil.isBlank(dto.getTitle()) || dto.getTitle().length() < 4 ||
                StrUtil.isBlank(dto.getLabels())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        WmNews wmNews = new WmNews();
        List<String> images = new ArrayList<>();
        BeanUtils.copyProperties(dto, wmNews);
        //设置一些必要的参数
        wmNews.setUserId(WmThreadLocalUtil.getUser().getId());
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        //获取内容中的图片
        if (wmNews.getType() == -1) {
            images = getImages(wmNews);
            List<String> images1 = extracted(wmNews, images);
            String join = StringUtils.join(images1, ",");
            wmNews.setImages(join);
        }
        //首先先判断是新增还是修改文章
        if (dto.getId() == null) {
            //新增
            save(wmNews);
        } else {
            //修改  删除所有已经关联的素材库
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery()
                    .eq(WmNewsMaterial::getNewsId, wmNews.getId()));
            //修改
            updateById(wmNews);
        }
        //保存草稿还是发布
        //判断是否保存草稿
        if (dto.getStatus() == 0) {
            //保存成草稿
            //直接返回
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } else if (dto.getStatus() == 1) {
            //直接发布
            if (dto.getChannelId() == null || dto.getPublishTime() == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            //维系关系中间表，自媒体图文引用素材信息表
            WmNewsMaterial wmNewsMaterial = new WmNewsMaterial();
            //封面图片列表
            images = Arrays.asList(wmNews.getImages().split(","));
            images.forEach(s -> {
                wmNewsMaterial.setNewsId(wmNews.getId());
                wmNewsMaterial.setMaterialId(wmMaterialMapper
                        .selectOne(Wrappers.<WmMaterial>lambdaQuery()
                                .eq(WmMaterial::getUrl, s)).getId());
                //设置 类型
                wmNewsMaterial.setType((short) 1);
                wmNewsMaterialMapper.insert(wmNewsMaterial);
            });
            //再进行处理内容引用的内容
            images.forEach(s -> {
                wmNewsMaterial.setNewsId(wmNews.getId());
                wmNewsMaterial.setMaterialId(wmMaterialMapper
                        .selectOne(Wrappers.<WmMaterial>lambdaQuery()
                                .eq(WmMaterial::getUrl, s)).getId());
                wmNewsMaterial.setType((short) 0);
                wmNewsMaterialMapper.insert(wmNewsMaterial);
            });

        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        /**
         * 自动审核媒体文章
         */
        wmNewAutoScanService.autoScanMediaNews(wmNews.getId());
        //6.返回数据
        return ResponseResult.okResult("发布文章完成");
    }

    private List<String> extracted(WmNews dto, List<String> images) {

//        if (dto.getType() == 0) {
//            //无图
//            return  null;
//        } else if (dto.getType() == 1) {
//            //寻找一张图
//            WmNews
//
//        } else if (dto.getType() == 3) {
//            //多图 选3张图
//        } else
//            if (dto.getType() == -1) {
        //自动
        int size = images.size();
        if (size >= 3) {
            dto.setType((short) 3);
            images = images.stream().limit(3).collect(Collectors.toList());
        } else if (size >= 1) {
            dto.setType((short) 1);
            images = images.stream().limit(1).collect(Collectors.toList());
        } else {
            dto.setType((short) 0);
        }
//        }
        return images;
    }

    /**
     * 获取内容中的图片
     */
    private List<String> getImages(WmNews wmNews) {
        List<String> images = new ArrayList<>();
        String content = wmNews.getContent();
        if (StrUtil.isBlank(content)) {
            return images;
        }
        List<Map> maps = JSONArray.parseArray(content, Map.class);
        if (CollectionUtils.isEmpty(maps)) {
            return images;
        }
        for (Map map : maps) {
            String type = map.get("type") + "";
            if ("image".equals(type)) {
                String url = map.get("value") + "";
                images.add(url);
            }
        }
        return images;
    }

    /**
     * 删除文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delNews(Integer id) {
        //健壮性判断
        if (id == null) {
            throw new RuntimeException("文章id不能为空");
        }
        boolean b = this.removeById(id);
        if (!b) {
            //删除关联表数据
            throw new RuntimeException("删除文章失败");
        }
        //判断是否关联
        Integer i = wmNewsMaterialMapper.selectCount(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, id));
        if (i > 0) {
            //删除关联表数据
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, id));
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 文章上下架
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //完成文章的上下架
        //首先进行健壮性判断
        if (dto.getId() == null) {
            throw new RuntimeException(String.valueOf(AppHttpCodeEnum.PARAM_REQUIRE));
        }
        //判断文章是否存在
        WmNews wmNews = this.getById(dto.getId());
        if (wmNews == null) {
            throw new RuntimeException(String.valueOf(AppHttpCodeEnum.DATA_NOT_EXIST));
        }
        //判断文章状态
        if (!wmNews.getStatus().equals(WmNews.Status.PUBLISHED.getCode())) {
            throw new RuntimeException(String.valueOf(AppHttpCodeEnum.PARAM_INVALID));
        }
        //修改文章的状态(下架是0 上架是1)
        wmNews.setEnable(dto.getEnable());
        //更新文章
        boolean b = this.updateById(wmNews);
        if (!b) {
            throw new RuntimeException(String.valueOf(AppHttpCodeEnum.SERVER_ERROR));
        }
        log.info("文章更新成功,id,{}", wmNews.getId());
        log.info("通过mq发送消息给app端,message:{}", wmNews);
        //通过mq发送消息给app端（articled与enable）
        //将对象转换成JSON
        String json = JSON.toJSONString(wmNews);
        Message message = MessageBuilder.withBody(json.getBytes(StandardCharsets.UTF_8))
                .setContentType(MessageProperties.CONTENT_TYPE_JSON)
                .build();
        rabbitTemplate.convertAndSend(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,
                WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_ROUTINGKEY, message);
        log.info("通过mq，发送消息成功");
        return ResponseResult.okResult("文章上下架完成");
    }
}
